package com.usian.article.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.article.mapper.ApArticleConfigMapper;
import com.usian.article.mapper.ApArticleContentMapper;
import com.usian.article.mapper.ApArticleMapper;
import com.usian.article.service.ApArticleService;
import com.usian.model.article.dtos.ArticleHomeDto;
import com.usian.model.article.dtos.ArticleInfoDto;
import com.usian.model.article.pojos.ApArticle;
import com.usian.model.article.pojos.ApArticleConfig;
import com.usian.model.article.pojos.ApArticleContent;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    @Autowired
    private ApArticleMapper apArticleMapper;
    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;
    @Autowired
    private ApArticleContentMapper apArticleContentMapper;

    @Override
    public ResponseResult load(Short loadtype, ArticleHomeDto dto) {

        Integer size = dto.getSize();
        if(size==null ||size==0){
            size =10;
        }
        dto.setSize(size);

        if(loadtype!=0 && !(loadtype>0&&loadtype<3)){
            loadtype=1;
        }

        //判断时间
        if(dto.getMaxBehotTime()==null){
            dto.setMaxBehotTime(new Date());
        }

        //频道
        if(StringUtils.isEmpty(dto.getTag())){
            dto.setTag("__all__");
        }
        List<ApArticle> articleList = apArticleMapper.findList(dto, loadtype);
        ResponseResult responseResult = ResponseResult.okResult(articleList);
        return responseResult;
    }

    @Override
    public ResponseResult loadArticleInfo(ArticleInfoDto dto) {
        Map<String,Object> result =new HashMap<>();
        //1：校验参数
        if(dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2: 查询文章配置 config
        ApArticleConfig apArticleConfig = apArticleConfigMapper.findByArticleId(dto.getArticleId());

        if(apArticleConfig!=null){
            //3: 查询文章内容 content
            ApArticleContent apArticleContent = apArticleContentMapper.findByArticleId(dto.getArticleId());
            result.put("content",apArticleContent);
            result.put("config",apArticleConfig);
        }else{
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_ARTICLE_EXIST);
        }
        return ResponseResult.okResult(result);
    }
}
